package com.example.cms.Doctors;
import com.example.cms.DB.DBUtil;
import com.example.cms.Users.*;
import com.example.cms.Schedules.*;
import java.sql.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class DoctorsManager {
    private Scanner scanner;
    private UserService userService;
    private SchedulesManager schedulesManager;
    private User currentUser;

    // 日期时间格式化器
    private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public DoctorsManager() {
        this.scanner = new Scanner(System.in);
    }
    // ==================== 医生管理 ====================
    public void showDoctorMenu() {
        while (true) {
            System.out.println("\n--- 医生管理 ---");
            System.out.println("1. 添加医生");
            System.out.println("2. 查看医生信息");
            System.out.println("3. 修改医生信息");
            System.out.println("4. 查看医生列表");
            System.out.println("5. 设置医生排班");
            System.out.println("0. 返回主菜单");

            System.out.print("请选择操作: ");
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    addDoctor();
                    break;
                case "2":
                    viewDoctor();
                    break;
                case "3":
                    updateDoctor();
                    break;
                case "4":
                    listDoctors();
                    break;
                case "5":
                    setDoctorSchedule();
                    break;
                case "0":
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void addDoctor() {
        System.out.println("\n--- 添加医生 ---");
        try {
            System.out.print("工号: ");
            String doctorNo = scanner.nextLine();

            System.out.print("姓名: ");
            String name = scanner.nextLine();

            System.out.print("科室ID: ");
            int departmentId = Integer.parseInt(scanner.nextLine());

            System.out.print("职称: ");
            String title = scanner.nextLine();

            System.out.print("专业特长: ");
            String specialty = scanner.nextLine();

            System.out.print("工作年限: ");
            int workYears = Integer.parseInt(scanner.nextLine());

            System.out.print("学历: ");
            String education = scanner.nextLine();

            System.out.print("邮箱: ");
            String email = scanner.nextLine();

            System.out.print("诊费: ");
            double consultationFee = Double.parseDouble(scanner.nextLine());

            Doctor doctor = new Doctor(doctorNo, name, departmentId, title, specialty);
            doctor.setWorkYears(workYears);
            doctor.setEducation(education);
            doctor.setEmail(email);
            doctor.setConsultationFee(consultationFee);

            if (addDoctorToDB(doctor)) {
                // 同时创建用户账号
                User user = new User(doctorNo, "123456", "DOCTOR", name);
                if (userService.addUser(user)) {
                    System.out.println("医生添加成功！默认密码：123456");
                } else {
                    System.out.println("医生添加成功，但用户账号创建失败！");
                }
            } else {
                System.out.println("医生添加失败！");
            }
        } catch (Exception e) {
            System.out.println("添加失败: " + e.getMessage());
        }
    }
    private void viewDoctor() {
        System.out.println("\n--- 查看医生信息 ---");
        System.out.print("请输入医生ID: ");
        String input = scanner.nextLine();

        try {
            Doctor doctor = findDoctorById(Integer.parseInt(input));

            if (doctor != null) {
                displayDoctorInfo(doctor);
            } else {
                System.out.println("未找到医生信息！");
            }
        } catch (Exception e) {
            System.out.println("查询失败: " + e.getMessage());
        }
    }

    private void updateDoctor() {
        System.out.println("\n--- 修改医生信息 ---");
        System.out.print("请输入医生ID: ");
        int doctorId = Integer.parseInt(scanner.nextLine());

        try {
            Doctor doctor = findDoctorById(doctorId);
            if (doctor == null) {
                System.out.println("医生不存在！");
                return;
            }

            displayDoctorInfo(doctor);
            System.out.println("\n请输入要修改的信息(留空保持不变):");

            System.out.print("职称[" + doctor.getTitle() + "]: ");
            String title = scanner.nextLine();
            if (!title.isEmpty()) doctor.setTitle(title);

            System.out.print("专业特长[" + doctor.getSpecialty() + "]: ");
            String specialty = scanner.nextLine();
            if (!specialty.isEmpty()) doctor.setSpecialty(specialty);

            System.out.print("邮箱[" + doctor.getEmail() + "]: ");
            String email = scanner.nextLine();
            if (!email.isEmpty()) doctor.setEmail(email);

            System.out.print("诊费[" + doctor.getConsultationFee() + "]: ");
            String feeStr = scanner.nextLine();
            if (!feeStr.isEmpty()) doctor.setConsultationFee(Double.parseDouble(feeStr));

            if (updateDoctorInDB(doctor)) {
                System.out.println("医生信息更新成功！");
            } else {
                System.out.println("医生信息更新失败！");
            }
        } catch (Exception e) {
            System.out.println("修改失败: " + e.getMessage());
        }
    }

    private void listDoctors() {
        System.out.println("\n--- 医生列表 ---");
        try {
            List<Doctor> doctors = getAllDoctors();
            if (doctors.isEmpty()) {
                System.out.println("暂无医生数据");
                return;
            }

            System.out.println("ID\t工号\t姓名\t职称\t科室\t专业");
            System.out.println("------------------------------------------------");
            for (Doctor doctor : doctors) {
                System.out.printf("%d\t%s\t%s\t%s\t%s\t%s\n",
                        doctor.getDoctorId(),
                        doctor.getDoctorNo(),
                        doctor.getName(),
                        doctor.getTitle(),
                        doctor.getDepartmentName(),
                        doctor.getSpecialty());
            }
        } catch (Exception e) {
            System.out.println("获取医生列表失败: " + e.getMessage());
        }
    }

    private void setDoctorSchedule() {
        System.out.println("\n--- 设置医生排班 ---");
        System.out.print("请输入医生ID: ");
        int doctorId = Integer.parseInt(scanner.nextLine());

        try {
            Doctor doctor = findDoctorById(doctorId);
            if (doctor == null) {
                System.out.println("医生不存在！");
                return;
            }

            System.out.print("排班日期(YYYY-MM-DD): ");
            LocalDate scheduleDate = LocalDate.parse(scanner.nextLine(), dateFormatter);

            System.out.print("时间段(如: 上午/下午): ");
            String timeSlot = scanner.nextLine();

            System.out.print("诊室号: ");
            String roomNumber = scanner.nextLine();

            System.out.print("诊费: ");
            double fee = Double.parseDouble(scanner.nextLine());

            Schedule schedule = new Schedule(doctorId, scheduleDate, timeSlot);
            schedule.setRoomNumber(roomNumber);
            schedule.setFee(fee);

            if (schedulesManager.addSchedule(schedule)) {
                System.out.println("排班设置成功！");
            } else {
                System.out.println("排班设置失败！");
            }
        } catch (Exception e) {
            System.out.println("设置失败: " + e.getMessage());
        }
    }
    private void displayDoctorInfo(Doctor doctor) {
        System.out.println("\n=== 医生信息 ===");
        System.out.println("医生ID: " + doctor.getDoctorId());
        System.out.println("工号: " + doctor.getDoctorNo());
        System.out.println("姓名: " + doctor.getName());
        System.out.println("科室: " + doctor.getDepartmentName());
        System.out.println("职称: " + doctor.getTitle());
        System.out.println("专业特长: " + doctor.getSpecialty());
        System.out.println("工作年限: " + doctor.getWorkYears());
        System.out.println("学历: " + doctor.getEducation());
        System.out.println("邮箱: " + doctor.getEmail());
        System.out.println("诊费: " + doctor.getConsultationFee());
        System.out.println("状态: " + doctor.getStatus());
    }
    // 医生相关操作方法
    private boolean addDoctorToDB(Doctor doctor) {
        String sql = "INSERT INTO doctors (doctor_no, name, department_id, title, specialty, " +
                "work_years, education, email, consultation_fee) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            pstmt.setString(1, doctor.getDoctorNo());
            pstmt.setString(2, doctor.getName());
            pstmt.setInt(3, doctor.getDepartmentId());
            pstmt.setString(4, doctor.getTitle());
            pstmt.setString(5, doctor.getSpecialty());
            pstmt.setInt(6, doctor.getWorkYears());
            pstmt.setString(7, doctor.getEducation());
            pstmt.setString(8, doctor.getEmail());
            pstmt.setDouble(9, doctor.getConsultationFee());

            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                try (ResultSet rs = pstmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        doctor.setDoctorId(rs.getInt(1));
                    }
                }
                return true;
            }
        } catch (SQLException e) {
            System.err.println("添加医生失败: " + e.getMessage());
        }
        return false;
    }

    private Doctor findDoctorById(int doctorId) {
        String sql = "SELECT d.*, dept.dept_name FROM doctors d " +
                "LEFT JOIN departments dept ON d.department_id = dept.department_id " +
                "WHERE d.doctor_id = ?";

        try (   Connection conn = DBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, doctorId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return mapResultSetToDoctor(rs);
                }
            }
        } catch (SQLException e) {
            System.err.println("查询医生失败: " + e.getMessage());
        }
        return null;
    }

    public Doctor findDoctorByUserId(int userId) {
        String sql = "SELECT d.*, dept.dept_name FROM doctors d " +
                "LEFT JOIN departments dept ON d.department_id = dept.department_id " +
                "JOIN users u ON d.name = u.name WHERE u.id = ?";

        try (   Connection conn = DBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return mapResultSetToDoctor(rs);
                }
            }
        } catch (SQLException e) {
            System.err.println("通过用户ID查询医生失败: " + e.getMessage());
        }
        return null;
    }

    private boolean updateDoctorInDB(Doctor doctor) {
        String sql = "UPDATE doctors SET doctor_no = ?, name = ?, department_id = ?, title = ?, " +
                "specialty = ?, work_years = ?, education = ?, email = ?, consultation_fee = ? " +
                "WHERE doctor_id = ?";

        try (    Connection conn = DBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, doctor.getDoctorNo());
            pstmt.setString(2, doctor.getName());
            pstmt.setInt(3, doctor.getDepartmentId());
            pstmt.setString(4, doctor.getTitle());
            pstmt.setString(5, doctor.getSpecialty());
            pstmt.setInt(6, doctor.getWorkYears());
            pstmt.setString(7, doctor.getEducation());
            pstmt.setString(8, doctor.getEmail());
            pstmt.setDouble(9, doctor.getConsultationFee());
            pstmt.setInt(10, doctor.getDoctorId());

            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            System.err.println("更新医生失败: " + e.getMessage());
        }
        return false;
    }

    private List<Doctor> getAllDoctors() {
        List<Doctor> doctors = new ArrayList<>();
        String sql = "SELECT d.*, dept.dept_name FROM doctors d " +
                "LEFT JOIN departments dept ON d.department_id = dept.department_id " +
                "ORDER BY d.create_time DESC";

        try (   Connection conn = DBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                doctors.add(mapResultSetToDoctor(rs));
            }
        } catch (SQLException e) {
            System.err.println("获取所有医生失败: " + e.getMessage());
        }
        return doctors;
    }
    public Doctor mapResultSetToDoctor(ResultSet rs) throws SQLException {
        Doctor doctor = new Doctor();
        doctor.setDoctorId(rs.getInt("doctor_id"));
        doctor.setDoctorNo(rs.getString("doctor_no"));
        doctor.setName(rs.getString("name"));
        doctor.setDepartmentId(rs.getInt("department_id"));
        doctor.setTitle(rs.getString("title"));
        doctor.setSpecialty(rs.getString("specialty"));
        doctor.setWorkYears(rs.getInt("work_years"));
        doctor.setEducation(rs.getString("education"));
        doctor.setEmail(rs.getString("email"));
        doctor.setConsultationFee(rs.getDouble("consultation_fee"));
        doctor.setStatus(rs.getString("status"));
        // 额外信息
        doctor.setDepartmentName(rs.getString("dept_name"));
        return doctor;
    }

    public void setSchedulesManager(SchedulesManager schedulesManager) {
        this.schedulesManager = schedulesManager;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setCurrentUser(User currentUser) {
        this.currentUser = currentUser;
    }


}
